package com.qf.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    /**
     * 查询对象存储数据列表
     * @param key    根据文件的key进行查找
     * @param name   根据文件名字查找
     * @param page   当前页, 默认值1
     * @param limit  每页显示条数, 默认值10
     * @param sort   排序字段名, 默认按照add_time添加时间排序
     * @param order  排序方式, 默认desc降序
     * @return
     */
    @GetMapping("/list")
    public Object list(String key,String name,
                       @RequestParam(defaultValue = "1")Integer page,
                       @RequestParam(defaultValue = "10")Integer limit,
                       @RequestParam(defaultValue = "add_time")String sort,
                       @RequestParam(defaultValue = "desc")String order){
        IPage<DtsStorage> iPage = storageService.queryStoragePage(key, name, page, limit, sort, order);
        List<DtsStorage> list = iPage.getRecords();
        long total = iPage.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("total",total);
        data.put("items",list);
        return ResponseUtil.ok(data);
    }

    /**
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/create")
    public Object createStorage(@RequestParam("file") MultipartFile file)throws Exception{
        //获得文件名

        String name = file.getOriginalFilename();
        if(StringUtils.isEmpty(name)){
            throw new RuntimeException("上传的文件为空, 不允许上传!");
        }
        //获得文件扩展名
        String extension = name.substring(name.lastIndexOf("."));
        //获得文件大小
        long size = file.getSize();
        //获得文件内容
        byte[] bytes = file.getBytes();
        DtsStorage storage = storageService.insertStorage(name,(int) size, extension, bytes);
        return ResponseUtil.ok(storage);

    }
    @PostMapping("/update")
    public Object updateStorage(@RequestBody DtsStorage storage){
        int count = storageService.updateStorage(storage);
        if (count==0){
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok();
    }
    @PostMapping("/delete")
    public Object deleteStorage(@RequestBody DtsStorage storage){
        String key = storage.getKey();
        if (StringUtils.isEmpty(key)){
            return ResponseUtil.badArgument();
        }
        storageService.deleteStorage(key);

        return ResponseUtil.ok();
    }
}
